/*
 * Copyright (C) 2009 nyapr.net
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.nyapr.anime.logic;

import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

/**
 * @author Yamitake
 */
public class SoundPlayerImpl implements SoundPlayer
{
    @Override
    public void playCall()
    {
        playSound(callSoundUrl);

    }

    @Override
    public void playUndo()
    {
        playSound(undoSoundUrl);
    }

    /**
     * URLで指定された、音声ファイルを再生する。
     * 
     * @param url
     */
    private void playSound(final URL url)
    {
        // logger.debug("play sound url:" + url);

        try
        {
            final AudioInputStream sound = AudioSystem.getAudioInputStream(url);
            final AudioFormat format = sound.getFormat();
            final DataLine.Info di = new DataLine.Info(Clip.class, format);
            final Clip clip = (Clip) AudioSystem.getLine(di);
            clip.open(sound);
            clip.start();
        }
        catch (final UnsupportedAudioFileException e)
        {
            e.printStackTrace();
        }
        catch (final IOException e)
        {
            e.printStackTrace();
        }
        catch (final LineUnavailableException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * サウンド管理読み込み
     */
    @Inject
    public SoundPlayerImpl()
    {
        callSoundUrl = getClass().getResource("/sound/effects/save.wav");
        undoSoundUrl = getClass().getResource("/sound/effects/undo.wav");
        logger.debug("Initialization sound manager");
    }

    final private URL callSoundUrl;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    final private URL undoSoundUrl;
}
